﻿using Hangjing.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

using Newtonsoft.Json;
using Hangjing.Model;
using Hangjing.SQLServerDAL;
using Hangjing.WebCommon;

namespace Hangjing.EleAPI
{
    public class baseEleAPI
    {
        public HttpContext context = null;

        /// <summary>
        /// 参数列表
        /// </summary>
        private Hashtable parameters;


        /** debug信息 */
        private string debugInfo;

        /** 获取debug信息 */
        public String getDebugInfo()
        {
            return debugInfo;
        }

        /** 设置debug信息 */
        public void setDebugInfo(String debugInfo)
        {
            this.debugInfo = debugInfo;
        }

        /// <summary>
        /// 访问链接
        /// </summary>
        public string serverurl
        {
            set;
            get;
        }

        /// <summary>
        /// 
        /// </summary>
        public virtual void init(HttpContext _context)
        {
            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());
            context = _context;

        }

        /** 获取参数值 */
        public string getParameter(string parameter)
        {
            string s = (string)parameters[parameter];
            return (null == s) ? "" : s;
        }

        /** 设置参数值 */
        public void setParameter(string parameter, string parameterValue)
        {
            if (parameter != null && parameter != "")
            {
                if (parameters.Contains(parameter))
                {
                    parameters.Remove(parameter);
                }

                parameters.Add(parameter, parameterValue);
            }
        }

        /// <summary>
        /// sha1签名
        /// </summary>
        /// <returns></returns>
        public string createSHA1Sign(string url)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();

            foreach (string k in akeys)
            {
                string v = HttpUtility.UrlEncode((string)parameters[k], Encoding.UTF8);
                if (null != v && "".CompareTo(v) != 0
                       && "sig".CompareTo(k) != 0)
                {
                    if (sb.Length == 0)
                    {
                        sb.Append(k + "=" + v);
                    }
                    else
                    {
                        sb.Append("&" + k + "=" + v);
                    }
                }
            }


            string signstep2 = url + "?" + sb.ToString() + EleUtil.consumer_secret;

            signstep2 = signstep2.Replace("%2c", "%2C");

            string signstep3 = EleUtil.StringToHexString(signstep2).ToLower();
            string sig = EleUtil.SHA1_Hash(signstep3).ToLower();


            //debug信息
            this.setDebugInfo("signstep1=" + sb.ToString() + "\r\nsignstep2=" + signstep2 + "\r\nsignstep3=" + signstep3 + "\r\n => sign:" + sig);



            return sig;
        }

        /// <summary>
        /// 请求新订单
        /// </summary>
        /// <returns></returns>
        public IList<ShopDataInfo> queryNewOrder()
        {
            IList<ShopDataInfo> orders = new List<ShopDataInfo>();

            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "GET"
            };

            int hasorder = 0;

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());

            string returnmsg = queryData(objHttpItem, APIUrl.neworder);
            NewOrdersInfo neworders = JsonConvert.DeserializeObject<NewOrdersInfo>(returnmsg);

            Hangjing.AppLog.AppLog.Info("订单数据：" + neworders.data.order_ids.Length);

            if (neworders != null && neworders.data != null && neworders.data.order_ids != null)
            {
                foreach (var item in neworders.data.order_ids)
                {
                    eleOrder orderinfo = QueryOrderByID(item);
                    if (orderinfo.data != null)
                    {
                        if (receiveOrder(orderinfo.data.order_id))
                        {
                            AddOrder(orderinfo);

                            orders.Add(new ShopDataInfo()
                            {
                                classname = orderinfo.data.user_id,
                                Pic = orderinfo.data.order_id
                            });


                        }

                    }
                    //添加数据库


                }
            }

            return orders;
        }


        /// 请求新订单
        /// </summary>
        /// <returns></returns>
        public IList<ShopDataInfo> queryNewOrder_test()
        {
            IList<ShopDataInfo> orders = new List<ShopDataInfo>();

            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "GET"
            };

            int hasorder = 0;

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());

            string returnmsg = queryData(objHttpItem, APIUrl.neworder);
            NewOrdersInfo neworders = JsonConvert.DeserializeObject<NewOrdersInfo>(returnmsg);

            Hangjing.AppLog.AppLog.Info("订单数据：" + neworders.data.order_ids.Length);

            if (neworders != null && neworders.data != null && neworders.data.order_ids != null)
            {
                int index = 0;
                foreach (var item in neworders.data.order_ids)
                {

                    eleOrder orderinfo = QueryOrderByID(item);
                    if (orderinfo.data != null)
                    {
                        index++;
                        AddOrder(orderinfo);
                    }
                    //添加数据库

                    if (index > 12)
                    {
                        break;
                    }

                }
            }

            return orders;
        }


        /// <summary>
        /// 拉取新订单
        /// </summary>
        /// <returns></returns>
        public IList<ShopDataInfo> queryPullNewOrder()
        {
            IList<ShopDataInfo> orders = new List<ShopDataInfo>();

            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "GET"
            };

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());

            string returnmsg = queryData(objHttpItem, APIUrl.pullorder);
            NewOrdersInfo neworders = JsonConvert.DeserializeObject<NewOrdersInfo>(returnmsg);

            Hangjing.AppLog.AppLog.Info("queryPullNewOrder:订单数据：" + neworders.data.order_ids.Length);

            if (neworders != null && neworders.data != null && neworders.data.order_ids != null)
            {

                string successIDs = "";

                foreach (var item in neworders.data.order_ids.Take(10))
                {
                    eleOrder orderinfo = QueryOrderByID(item);
                    if (orderinfo.data != null)
                    {
                        if (AddOrder(orderinfo) > 0)
                        {
                            orders.Add(new ShopDataInfo()
                            {
                                classname = orderinfo.data.user_id,
                                Pic = orderinfo.data.order_id
                            });
                        }


                        successIDs += orderinfo.data.order_id + ",";

                    }
                    //添加数据库

                }
                successIDs = Utils.dellast(successIDs);
                if (successIDs.Length > 0)
                {
                    pullOrderRollback(successIDs);
                }
            }

            return orders;
        }




        /// <summary>
        /// 添加订单到数据库
        /// </summary>
        /// <param name="orderinfo"></param>
        /// <returns></returns>
        public int AddOrder(eleOrder orderinfo)
        {
            shopeleCustorder dal = new shopeleCustorder();


            CustorderInfo infos = new CustorderInfo();
            infos.orderid = "e" + orderinfo.data.order_id.ToString(); ;
            if (dal.GetCount("orderid = '"+ infos.orderid + "'") > 0)
            {
                return 0;
            }


            //1.加到系统，
            Custorder ordermodel = new Custorder();


         

            decimal allfoodmoney = 0;

            int qty = 0;
            PointsInfo togomodel = new Points().GetSendFeeModelByEleNO(orderinfo.data.restaurant_id.ToString());

            if (togomodel == null)
            {
                HJlog.toLog(" 商家（" + orderinfo.data.restaurant_id.ToString() + "）（" + orderinfo.data.restaurant_name + "）未在系统对应");
                return 0;
            }


            IList<Hangjing.Model.ETogoShoppingCart> Foods = new List<Hangjing.Model.ETogoShoppingCart>();

            Hangjing.Model.ETogoShoppingCart myshopcart = new Hangjing.Model.ETogoShoppingCart();
            myshopcart.TogoId = togomodel.Unid;
            myshopcart.sendfree = 0;
            //满多少元免配送费未处理
            myshopcart.ItemList = null;

            IList<ETogoShoppingCartInfo> foodlist = new List<ETogoShoppingCartInfo>();

            foreach (var item in orderinfo.data.detail.group)
            {
                foreach (var food in item)
                {
                    ETogoShoppingCartInfo cartfood = new ETogoShoppingCartInfo();

                    cartfood.PId = food.id;
                    cartfood.PName = food.name;
                    cartfood.PNum = food.quantity;
                    cartfood.PPrice = food.price;
                    cartfood.Currentprice = cartfood.PPrice;
                    cartfood.Foodcurrentprice = cartfood.PPrice;
                    cartfood.Remark = "";


                    allfoodmoney += cartfood.PPrice * cartfood.PNum;
                    qty += cartfood.PNum;

                    foodlist.Add(cartfood);
                }

            }
            myshopcart.ItemList = foodlist;
            Foods.Add(myshopcart);




            infos.OrderAddress = orderinfo.data.restaurant_name;

            infos.OrderRcver = orderinfo.data.consignee;
            infos.OrderComm = orderinfo.data.phone_list[0];
            infos.OrderAttach = "";


            string Remark = orderinfo.data.description;

            if (orderinfo.data.invoiced == 1)
            {
                Remark += "[发票：" + orderinfo.data.invoice + "]";
            }
            Remark += "[饿了么" + orderinfo.data.restaurant_number + "号单]";

            infos.OrderAttach = Remark;

            infos.AddressText = orderinfo.data.address;
            infos.SendTime = DateTime.Now.AddMinutes(50);
            if (orderinfo.data.deliver_time != null)
            {
                if (orderinfo.data.deliver_time > DateTime.Now.AddMinutes(50))
                {
                    infos.SendTime = (DateTime)orderinfo.data.deliver_time;
                }
            }
           

            infos.cityid = 0;

            infos.fromweb = ((int)OrderSource.api).ToString();
            infos.tempcode = "";
            infos.tempcode = "";
            infos.CustomerName = "";
            infos.ReveVar1 = togomodel.sentorg;



            infos.OldPrice = allfoodmoney;

            infos.OrderSums = infos.OldPrice + orderinfo.data.package_fee;


            infos.TogoId = togomodel.Unid;
            infos.P2Sign = "";
            infos.paytime = Convert.ToDateTime("1970-1-1");
            infos.paymode = 4;
            infos.ReveDate1 = DateTime.Now;

            infos.cardids = "";


            infos.settlecycle = togomodel.PType;
            infos.Advance = 0;
            infos.Mergeorderremark = "";
            infos.SystemUserId = 0;
            infos.IsShopSet = 0;
            infos.ReveDate1 = DateTime.Now;

            IList<Hangjing.Model.ETogoShoppingCart> list = Foods;

            string ulat = "0";
            string ulng = "0";

            SendInfo model = new SendInfo();

            if (orderinfo.data.delivery_geo != null && orderinfo.data.delivery_geo.Length > 0)
            {
                string[] latlng = orderinfo.data.delivery_geo.Split(',');

                string[] bdlatlng = Hangjing.Common.HjNetHelper.bd_encrypt(Convert.ToDouble(latlng[0]), Convert.ToDouble(latlng[1]));
                ulat = bdlatlng[0];
                ulng = bdlatlng[1];

                SendfeeInfo info = new SendfeeInfo();
                info.ShopID = togomodel.Unid;
                info.userpay = infos.OrderSums;
                info.latlng = new latlnginfo();
                info.latlng.ulat = ulat;
                info.latlng.ulng = ulng;

                SendFee fee = new SendFee(info);
                model = fee.getSendFee();
            }





            infos.Commission = WebHelper.getShopCommission(allfoodmoney, togomodel);
            infos.shopdiscountmoney = model.sendmoney;
            infos.cardpay = model.Distance;

            infos.ReveVar2 = "{'ulat':'" + ulat + "','ulng':'" + ulng + "','slat':'" + togomodel.Lat + "','slng':'" + togomodel.Lng + "'}";

            foreach (Hangjing.Model.ETogoShoppingCart item in Foods)
            {
                item.latlng = infos.ReveVar2;
            }

            if (orderinfo.data.is_online_paid == 1)
            {
                infos.paystate = 1;
                infos.paymoney = orderinfo.data.total_price;
                infos.paymode = 1;
                infos.paytime = orderinfo.data.active_at;

            }



            ////这里进行所有的判断
            IList<ROrderinfo> mylist = dal.SubmitOrder(Foods, infos);

            if (mylist != null)
            {
                if (infos.paystate == 1)
                {
                    dal.UpdatePayState(infos);
                }

                return 1;

            }
            else
            {
                return 0;
            }

        }

        /// <summary>
        /// 查询单个订单
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public eleOrder QueryOrderByID(string orderid)
        {
            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "GET"

            };

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());


            string returnmsg = queryData(objHttpItem, APIUrl.orderinfo + orderid + "/");
            eleOrder order = JsonConvert.DeserializeObject<eleOrder>(returnmsg);

            HJlog.toLog("订单数据：" + returnmsg);

            return order;
        }


        /// <summary>
        /// 商家确认订单
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public bool receiveOrder(string orderid)
        {
            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "PUT",
                Postdata = "status=2"
            };

            string url = APIUrl.host + "/order/" + orderid + "/status/";

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());
            parameters.Add("status", "2");


            string returnmsg = queryData(objHttpItem, url);

            HJlog.toLog("订单确认：" + orderid + " returnmsg=" + returnmsg);

            BaseResultInfo order = JsonConvert.DeserializeObject<BaseResultInfo>(returnmsg);



            bool issuccess = true;
            if (order.code != 200)
            {
                issuccess = false;
            }

            return issuccess;
        }

        /// <summary>
        /// 更新餐厅接单模式
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public bool setorder_mode(string restaurant_id, string order_mode)
        {
            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "PUT",
                Postdata = "order_mode=" + order_mode
            };

            string url = APIUrl.host + "/restaurant/" + restaurant_id + "/order_mode/";

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());
            parameters.Add("order_mode", order_mode);

            string returnmsg = queryData(objHttpItem, url);

            HJlog.toLog("更新餐厅接单模式：" + restaurant_id + "(" + order_mode + ")" + " returnmsg=" + returnmsg);

            BaseResultInfo order = JsonConvert.DeserializeObject<BaseResultInfo>(returnmsg);



            bool issuccess = true;
            if (order.code != 200)
            {
                issuccess = false;
            }

            return issuccess;
        }


        /// <summary>
        /// 拉取订单回调
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public bool pullOrderRollback(string ids)
        {
            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "POST",
                Postdata = "order_ids=" + ids
            };

            string url = APIUrl.pullorderrollback;

            parameters = new Hashtable();
            parameters.Add("consumer_key", EleUtil.consumer_key);
            parameters.Add("timestamp", EleUtil.getTimestamp());
            parameters.Add("order_ids", ids);

            string returnmsg = queryData(objHttpItem, url);

            HJlog.toLog("拉取订单回调：" + ids + " returnmsg=" + returnmsg);

            BaseResultInfo order = JsonConvert.DeserializeObject<BaseResultInfo>(returnmsg);



            bool issuccess = true;
            if (order.code != 200)
            {
                issuccess = false;
            }

            return issuccess;
        }


        public string queryData(HttpItem objHttpItem, string url)
        {
            string sig = createSHA1Sign(url);
            parameters.Add("sig", sig);

            serverurl = url;
            ArrayList akeys = new ArrayList(parameters.Keys);

            StringBuilder sb = new StringBuilder();
            foreach (string k in akeys)
            {
                string v = context.Server.UrlEncode((string)parameters[k]);
                v = HttpUtility.UrlEncode(v, Encoding.UTF8);
                if (null != v && "".CompareTo(v) != 0)
                {
                    if (sb.Length == 0)
                    {
                        sb.Append(k + "=" + v);
                    }
                    else
                    {
                        sb.Append("&" + k + "=" + v);
                    }
                }
            }


            serverurl += "?" + sb.ToString();

            HttpHelper objhttp = new HttpHelper();
            objHttpItem.URL = serverurl;


            objhttp.isToLower = false;
            string returnmsg = objhttp.GetHtml(objHttpItem);

            Hangjing.Common.HJlog.toLog("returnmsg=" + returnmsg + "\r\n url=" + serverurl);
            //  HJlog.toLog(this.getDebugInfo());

            return returnmsg;
        }
    }


    /// <summary>
    /// 接口
    /// </summary>
    public class APIUrl
    {
        public static string host = "http://v2.openapi.ele.me";
        public static string neworder = host + "/order/new/";
        public static string orderinfo = host + "/order/";

        public static string pullorder = host + "/order/pull/new/"; //返回当前时间前30分钟的订单
        public static string pullorderrollback = host + "/order/pull/new/rollback/"; //标记订单是否被拉取过


    }

}
